package cn.easy.service.impl;

import cn.easy.api.DeviceService;
import cn.easy.common.util.ExceptionUtil;
import cn.easy.mapper.DeviceMapper;
import cn.easy.mapper.UserMapper;
import cn.easy.pojo.Device;
import cn.easy.pojo.DeviceExample;
import cn.easy.pojo.User;
import cn.easy.pojo.UserExample;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@Service
public class DeviceServiceImpl implements DeviceService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 验证用户身份
     *
     * @param deviceId
     * @param userKey
     * @return
     */
    private void checkUser(int deviceId, String userKey) throws Exception {
        //身份验证
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUserKeyEqualTo(userKey);
        List<User> users = userMapper.selectByExample(userExample);
        if (users.size() == 0) {
            throw new Exception("用户不存在");
        }
        User user = users.get(0);
        Device device = deviceMapper.selectByPrimaryKey(deviceId);
        if (device == null) {
            throw new Exception("设备不存在");
        }
        if (device.getUserId() != user.getUserId()) {
            //身份验证失败
            throw new Exception("身份验证失败，请检查key");
        }
    }

    /**
     * 新增设备
     *
     * @param device
     * @param userKey
     * @return
     */
    @Override
    public void insertDevice(Device device, String userKey) throws Exception {
        //判断设备必要信息是否填写
        if (device.getDeviceName() == null) {
            throw new Exception("参数缺失");
        }
        //通过userKey 找到操作用户
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUserKeyEqualTo(userKey);
        List<User> users = userMapper.selectByExample(example);
        if (users.size() == 0) throw new Exception("认证是失败，请检查key");
        //将设备添加到该用户名下
        device.setUserId(users.get(0).getUserId());
        //看是否设置了设备私有权限  没有设置默认为 公开
        if (device.getDevicePersonal() == null) device.setDevicePersonal(1);
        Date date = new Date();
        //设置创建时间
        device.setDeviceCreateTime(date);
        //设置更新时间
        device.setDeviceUpdateTime(date);
        //设置设备的状态为可用
        device.setDeviceState(1);
        //新增设备
        deviceMapper.insert(device);
    }

    /**
     * 删除一个设备  需要身份验证
     *
     * @param deviceId
     * @param userKey
     * @return
     */
    @Override
    public void deleteDevice(int deviceId, String userKey) throws Exception {
        //身份验证
        checkUser(deviceId, userKey);
        //删除设备
        deviceMapper.deleteByPrimaryKey(deviceId);
    }

    /**
     * 更新设备信息  需要身份验证
     *
     * @param device
     * @param userKey
     * @return -3=用户不存在
     * -2=设备不存在
     * -1=身份验证失败
     * 1=成功
     */
    @Override
    public void updateDevice(Device device, String userKey) throws Exception {
        //判断必要参数
        if (device.getDeviceId() == null) throw new Exception("缺少必要参数");//必要参数缺失
        //身份验证
        checkUser(device.getDeviceId(), userKey);
        Device oldDevice = deviceMapper.selectByPrimaryKey(device.getDeviceId());
        if (device.getDeviceDesc() != null) oldDevice.setDeviceDesc(device.getDeviceDesc());
        if (device.getDeviceLongitude() != null) oldDevice.setDeviceLongitude(device.getDeviceLongitude());
        if (device.getDeviceLatitude() != null) oldDevice.setDeviceLatitude(device.getDeviceLatitude());
        if (device.getDeviceState() != null) oldDevice.setDeviceState(device.getDeviceState());
        if (device.getDeviceTag() != null) oldDevice.setDeviceTag(device.getDeviceTag());
        if (device.getDevicePersonal() != null) oldDevice.setDevicePersonal(device.getDevicePersonal());
        if (device.getDeviceName() != null) oldDevice.setDeviceName(device.getDeviceName());
        //设置更新时间
        oldDevice.setDeviceUpdateTime(new Date());
        //更新设备
        deviceMapper.updateByPrimaryKeySelective(oldDevice);
    }

    /**
     * 查询用户名下所有的公开的设备
     *
     * @param userId
     * @return
     */
    @Override
    public List<Device> searchUserPublicDevice(int userId) {
        DeviceExample example = new DeviceExample();
        DeviceExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andDevicePersonalEqualTo(1);
        List<Device> deviceList = deviceMapper.selectByExample(example);
        return deviceList;
    }

    /**
     * 查询用户名下所有设备，包括公开和未公开的
     *
     * @param userKey
     * @return
     */
    @Override
    public List<Device> searchUserAllDevice(String userKey) {
        //通过userKey 找到操作用户
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUserKeyEqualTo(userKey);
        List<User> users = userMapper.selectByExample(example);
        if (users.size() == 0) return null;
        User user = users.get(0);
        //查询用户名下所有设备，包括公开和未公开的
        DeviceExample deviceExampleexample = new DeviceExample();
        DeviceExample.Criteria devcriteria = deviceExampleexample.createCriteria();
        devcriteria.andUserIdEqualTo(user.getUserId());
        List<Device> deviceList = deviceMapper.selectByExample(deviceExampleexample);
        return deviceList;
    }

    @Override
    public Device searchOneDevice(int deviceId, String userKey) throws Exception {
        String deviceNotExist = "设备不存在";
        String errorKey = "身份验证失败";
        Device device = deviceMapper.selectByPrimaryKey(deviceId);
        //判断设备是否存在
        if (device == null) {
            throw new Exception(deviceNotExist);
        }
        //判断设备是否公开
        if (device.getDevicePersonal() == 1) {
            return device;
        } else {
            //在设备是私有的情况下判断userKey
            Integer userId = device.getUserId();
            User user = userMapper.selectByPrimaryKey(userId);
            if (user.getUserKey().equals(userKey)) {
                return device;
            } else {
                throw new Exception(errorKey);
            }
        }
    }

    @Override
    public User getUserByDeviceKey(String deviceKey) throws Exception {
        DeviceExample deviceExample = new DeviceExample();
        DeviceExample.Criteria criteria = deviceExample.createCriteria();
        criteria.andDeviceKeyEqualTo(deviceKey);
        List<Device> list = deviceMapper.selectByExample(deviceExample);
        if(list.size() == 0){
            throw new Exception("找不到deviceKey对应的设备");
        }
        Device device = list.get(0);
        User user = userMapper.selectByPrimaryKey(device.getUserId());
        if(user == null){
            throw new Exception("在检测触发器阶段，找不到设备对应的用户");
        }
        return user;
    }
}
